<?php
namespace app\common\process;

use think\exception\ValidateException;

class Base {
	protected $request = null;
	protected $assignArr = [];
	protected $event = []; //流程内事件

    public static function factory() {
    	$args = func_get_args();
        return new static(...$args);
    }

    public function __construct() {
	}

	//添加事件
	public function event($name, $callback) {
		$this->event[$name][] = $callback;
	}

	//添加流程内事件
	public function trigger($name, $args = []) {
		$event = $this->event;
		if(isset($event[$name])) {
			$list = $event[$name];
			foreach($list as $k => $callback) {
				if (is_callable($callback)) {
                    $result = call_user_func_array($callback, $args);
                    if (false === $result) {
                        return false;
                    }
                }
			}
		}
	}

	public function assign($key, $value = '') {
		if(is_array($key)) {
			$this->assignArr = array_merge($this->assignArr, $key);
		} else {
			$this->assignArr[$key] = $value;
		}
	}

	public function error($msg) {
		throw new ValidateException($msg);
	}

	public function success($msg, $data = null) {
		$this->assign('__msg', $msg);
		if($data) {
			$this->assign('data', $data);
		}
		return $this->fetch();
	}

	public function fetch() {
		return $this->assignArr;
	}
}